import { defineStore } from 'pinia'
import { constantRoute, asyncRoute, anyRoute } from '@/router/routes'
import { reqUserInfo, reqUserLogout } from "@/api/user"
import router from '../../router/index'
import cloneDeep from 'loadsh/cloneDeep'

const filterAsyncRoutes = (asyncRoute: any, routes: any) => {
  return asyncRoute.filter(item => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoutes(item.children, routes)
      }
      return true;
    }
  })
}

const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    menuRoutes: constantRoute,
    userInfo: {},
    buttons:[]
  }),
  actions: {
    async getUserInfo() {
      const res = await reqUserInfo();
      if (res?.code == 200) {
        const userRoutes = filterAsyncRoutes(cloneDeep(asyncRoute),res.data?.routes)
        this.menuRoutes = [...constantRoute,...userRoutes,...anyRoute];
        this.buttons = res.data?.buttons || [];
        [...userRoutes,...anyRoute].forEach((item:any)=>{
            router.addRoute(item)
        })

        const _t = res.data instanceof Object;
        this.userInfo = _t ? res.data : {};
        return 'ok';
      } else return Promise.reject(new Error(res.message));
    },
    async exitLogin() {
      const res = await reqUserLogout()
      if (res.code === 200) {
        this.token = '';
        this.userInfo = {};
        localStorage.removeItem('token');
        return 'ok'
      }else {
        return Promise.reject(new Error(res.message))
      }
    }
  },
  persist: false
})

export default useUserStore